package one_one

import (
	"producer-consumer/out"
	"sync"
	"time"
)

type Task struct {
	ID int64
}

func (t Task) run() {
	out.Println(t.ID)
}

const taskNum int64 = 100000

var (
	startTime time.Time
	endTime   time.Time
)

var taskCh = make(chan Task)

func producer(wo chan<- Task) {
	var i int64
	for i = 1; i <= taskNum; i++ {
		t := Task{
			ID: i,
		}
		wo <- t
	}
	close(wo)
}

func consumer(ro <-chan Task) {
	for t := range ro {
		if t.ID != 0 {
			t.run()
		}
	}
}

func Exec() {
	startTime = time.Now()
	wg := &sync.WaitGroup{}
	wg.Add(2)
	go func(wg *sync.WaitGroup) {
		defer wg.Done()
		producer(taskCh)
	}(wg)
	go func() {
		defer wg.Done()
		consumer(taskCh)
	}()
	wg.Wait()
	endTime = time.Now()
	out.Println(endTime.Sub(startTime))
}
